﻿using Microsoft.Extensions.Options;
using MongoDB.Driver;
using SubStationManagement.Server.Models;

namespace SubStationManagement.Server.Services
{
    public class DIDOModuleService
    {
        private readonly IMongoCollection<DIDOModule> _dIDOModulesCollection;

        public DIDOModuleService(
            IOptions<SubStationDatabaseSettings> subStationDatabaseSettings)
        {
            var mongoClient = new MongoClient(
                subStationDatabaseSettings.Value.ConnectionString);

            var mongoDatabase = mongoClient.GetDatabase(
                subStationDatabaseSettings.Value.DatabaseName);

            _dIDOModulesCollection = mongoDatabase.GetCollection<DIDOModule>(
                subStationDatabaseSettings.Value.DIDOModulesCollectionName);
        }

        public async Task<List<DIDOModule>> GetAsync() =>
            await _dIDOModulesCollection.Find(_ => true).ToListAsync();

        public async Task<DIDOModule?> GetAsync(string id) =>
            await _dIDOModulesCollection.Find(x => x.Id == id).FirstOrDefaultAsync();

        public List<DIDOModule> GetAll() =>
            _dIDOModulesCollection.Find(_ => true).ToList();

        public async Task CreateAsync(DIDOModule newDIDOModule) =>
            await _dIDOModulesCollection.InsertOneAsync(newDIDOModule);

        public async Task UpdateAsync(string id, DIDOModule updatedDIDOModule) =>
            await _dIDOModulesCollection.ReplaceOneAsync(x => x.Id == id, updatedDIDOModule);

        public async Task RemoveAsync(string id) =>
            await _dIDOModulesCollection.DeleteOneAsync(x => x.Id == id);
    }
}
